package asia.lxq.cic.service;

import asia.lxq.cic.config.GlobalConfig;
import asia.lxq.cic.dao.AreaMapper;
import asia.lxq.cic.dao.GroupMapper;
import asia.lxq.cic.dao.UserMapper;
import asia.lxq.cic.entity.Group;
import asia.lxq.cic.entity.Result;
import asia.lxq.cic.entity.User;
import asia.lxq.cic.util.RedisUtil;
import asia.lxq.cic.util.UserUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class GroupService {

    @Autowired
    GroupMapper groupMapper;
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    AreaMapper areaMapper;
    @Autowired
    UserMapper userMapper;

    public Result<Object> getGroupList(int page, int pageSize){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        User user= (User) redisUtil.get(GlobalConfig.PRE_USERINFO_REDIS+authentication.getPrincipal());
        user.query(areaMapper);
        QueryWrapper<Group> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("group_college_id",user.getCollegeId());
        Page<Group> groupPage= groupMapper.selectPage(new Page<>(page,pageSize),queryWrapper);
        List<Group> groupList = groupPage.getRecords();
        groupList.forEach(group -> group.query(userMapper,true));
        Map<String,Object> resultData=new HashMap<>();
        resultData.put("data",groupList);
        resultData.put("total",groupPage.getTotal());
        resultData.put("current",groupPage.getCurrent());
        resultData.put("pages",groupPage.getPages());
        return Result.success(resultData);
    }

    public Result<Object> getTeacherOfCollegeId(String username){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        User user= (User) redisUtil.get(GlobalConfig.PRE_USERINFO_REDIS+authentication.getPrincipal());
        user.query(areaMapper);
        int userCollegeId = user.getCollegeId();
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("role","老师").like("username","%"+username+"%")
                .like("belong","%,%,"+userCollegeId+",0");
        List<User> teacherList = userMapper.selectList(queryWrapper);
        teacherList.forEach(teacher-> teacher.query(areaMapper));
        return Result.success(teacherList);
    }

    public Result<Object> createGroup(Group group){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        User user= (User) redisUtil.get(GlobalConfig.PRE_USERINFO_REDIS+authentication.getPrincipal());
        user.query(areaMapper);
        group.setGroupId(0L);
        group.setGroupCollegeId(user.getCollegeId());
        groupMapper.insert(group);
        User leaderUser = userMapper.selectById(group.getGroupLeaderId());
        leaderUser.setBelong(UserUtil.groupBelong(leaderUser.getBelong(),group.getGroupId()));
        userMapper.updateById(leaderUser);
        return Result.success();
    }

    public Result<Object> getGroupMember(int groupId){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        User user= (User) redisUtil.get(GlobalConfig.PRE_USERINFO_REDIS+authentication.getPrincipal());
        user.query(areaMapper);
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.like("belong","%,%,"+user.getCollegeId()+"%,"+groupId);
        List<User> rememberList = userMapper.selectList(queryWrapper);
        return Result.success(rememberList);
    }

    public Result<Object> addMember(int[] userIds, int groupId){
        //TODO 此处隐藏了bug，因该在修改之前，检查该userId是否和管理员是同一个学校
        for (int userId : userIds) {
            User user = userMapper.selectById(userId);
            if (user==null)continue;
            String[] split = user.getBelong().split(",");
            split[3]=groupId+"";
            String belongFormatted = String.format("%s,%s,%s,%s", split[0], split[1], split[2], split[3]);
            user.setBelong(belongFormatted);
            userMapper.updateById(user);
        }
        return Result.success();
    }

    public Result<Object> removeMember(int userId){
        //TODO 此处隐藏了bug，因该在修改之前，检查该userId是否和管理员是同一个学校
        User user = userMapper.selectById(userId);
        user.query(areaMapper);
        String[] split = user.getBelong().split(",");
        split[3]="0";
        user.setBelong(String.format("%s,%s,%s,%s",split[0],split[1],split[2],split[3]));
        userMapper.updateById(user);
        return Result.success();
    }

    public Result<Object> groupUpdate(Group group){
        groupMapper.updateById(group);
        return Result.success();
    }

    public Result<Object> getUserOfCollegeId(String username) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        User user= (User) redisUtil.get(GlobalConfig.PRE_USERINFO_REDIS+authentication.getPrincipal());
        user.query(areaMapper);
        int userCollegeId = user.getCollegeId();
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("role","学生").like("username","%"+username+"%")
                .like("belong","%,%,"+userCollegeId+",0");
        List<User> userList = userMapper.selectList(queryWrapper);
        userList.forEach(teacher-> teacher.query(areaMapper));
        return Result.success(userList);
    }

    public Result<Object> searchGroupByName(int collegeId,String groupName){
        QueryWrapper<Group> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("group_College_Id",collegeId);
        queryWrapper.like("group_name",'%'+groupName+'%');
        List<Group> groupList = groupMapper.selectList(queryWrapper);
        groupList.forEach(group -> group.query(userMapper,false));
        return Result.success(groupList);
    }
}
